package com.itheima.case2.service.impl;

import com.itheima.case2.dao.UserMapper;
import com.itheima.case2.pojo.po.User;
import com.itheima.case2.pojo.vo.AddUser;
import com.itheima.case2.pojo.vo.PageResult;
import com.itheima.case2.pojo.vo.QueryPageBean;
import com.itheima.case2.pojo.vo.UpdateUser;
import com.itheima.case2.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public PageResult findByPage(QueryPageBean queryPageBean) {

        List<User> userByPage = userMapper.findUserByPage(queryPageBean);
        Long userTotal = userMapper.findUserTotal(queryPageBean);
        PageResult pageResult = new PageResult(userTotal,userByPage);
        return pageResult;
    }

    @Override
    public void addUser(AddUser addUser) {
        // 在t_user表中添加用户信息 （主键回填）
        userMapper.addUser(addUser);
        // 添加用户角色信息
        userMapper.addRoleByUid(addUser.getId(), addUser.getRoleIds());
    }

    @Override
    public void updateUser(UpdateUser updateUser) {
        //修改user表
        userMapper.updateUser(updateUser);
        //修改角色表
        userMapper.deleteRoleByUid(updateUser.getId());
        userMapper.addRoleByUid(updateUser.getId(), updateUser.getRoleIds());
    }

    @Override
    public void deleteUser(String uidStr) {
        int uid = Integer.parseInt(uidStr);
        //删除用户对应的角色中间表 根据userid
        userMapper.deleteRoleByUid(uid);
        //删除用户表 根据id
        userMapper.deleteUserById(uid);
    }
}
